package top.ewind.controller.admin.device;

import java.util.Date;

import org.eclipse.paho.client.mqttv3.IMqttClient;
import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.MqttCallback;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.eclipse.paho.client.mqttv3.MqttTopic;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.jfinal.aop.Clear;
import com.jfinal.kit.HttpKit;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;

import top.ewind.controller.common.AdminRootCtrl;
import top.ewind.model.SysDictory;
import top.ewind.util.DateUtil;
import top.ewind.util.LogicUtil;
import top.ewind.util.SecurityUtil;

public class ProductCtrl extends AdminRootCtrl {
	
	private static IMqttClient client = null;
	private static Logger LOG = LoggerFactory.getLogger(TestCtrl.class);
	public void index() {
		Record user = getSessionAttr("sysuser");
		String id = user.getInt("id").toString();
		String username = user.getStr("username");
		String pwd = user.getStr("pwd");
		setAttr("sid",id);
		setAttr("susername",username);
		setAttr("spwd",pwd);
		setAttr("mqttserver",SysDictory.getConfig("mqttserver"));
		render("index.html");
	}

	public void profile() {
		int nid = getSessionAttr("nid");
		String filter = "nid =" + nid + SecurityUtil.sqlFilter(getPara("param", ""));
		renderJson(Db.paginate(getParaToInt("page", 1), getParaToInt("rp", 10), "SELECT *", "from device_product where " + filter));
	}

	public void save() {
		int nid = getSessionAttr("nid");
		boolean ret = false;
		Record item = Db.findById("device_product", getPara("deviceProduct.id"));
		if (item!=null) {
			item.set("pname", getPara("deviceProduct.pname")).set("remark", getPara("deviceProduct.remark")).set("ptype", getPara("deviceProduct.ptype"));
			ret = Db.update("device_product",item);
		} else {
			Record items = new Record().set("id", LogicUtil.getTableId(16)).set("pmkey", LogicUtil.getTableId(32)).set("intime", new Date()).set("nid", nid).set("pname", getPara("deviceProduct.pname")).set("remark", getPara("deviceProduct.remark")).set("ptype", getPara("deviceProduct.ptype"));
			ret = Db.save("device_product", items);
		}
		if (ret)
			renderJson("msg", "success");
		else
			renderJson("msg", "保存失败，请重试！");
	}
	@Clear
	public void revice(){
		System.out.println("revice--------"+HttpKit.readData(getRequest()));
		renderNull();
	}
	
	/*public void connect(){		
		try {
			MqttConnectOptions options = new MqttConnectOptions();
			String[] clientid = getPara("cid").split("/");
			options.setUserName(clientid[1]);
			String pmkey = Db.queryStr("select t.pmkey from device_product t where t.id = ?",clientid[0]);
			Long timestamp = System.currentTimeMillis();
			String password = SecurityUtil.md5(pmkey+timestamp)+","+timestamp;
			options.setPassword(password.toCharArray());
			client = new MqttClient("tcp://"+SysDictory.getConfig("mqttserver")+":1880", getPara("cid"));
			MessageListener listener = new MessageListener();
	     	client.setCallback(listener);
			client.connect(options);
			client.subscribe("in/"+client.getClientId());
			renderJson("msg","success");
		} catch (MqttException e) {
			e.printStackTrace();
			renderJson("msg","出错了");
		}
	}
    */
	public void disconnect(){		
		try {
			client.disconnect();;
			renderJson("msg","success");
		} catch (MqttException e) {
			renderJson("msg","出错了");
		}
	}

	public void publish(){		
		//MqttTopic topic = client.getTopic("out/"+client.getClientId());
		//MqttMessage message = new MqttMessage(getPara("para").getBytes());
		//topic.publish(message);
		String messtitle = getPara("para").split(",")[0].toString();
		String messdetai = getPara("para").split(",")[1].toString();
		String mt = messtitle.split(":")[1].trim();
		String md = messdetai.split(":")[1].replaceAll("}", " ").trim();
		//String macid = client.getClientId().split("/")[1].toString(); 
		/*new UserMessage().set("title", mt).set("details", md)
		.set("mac", null).set("intime", new Date()).set("btype",1).save();
		renderJson("msg","success");*/
	}
	class MessageListener implements MqttCallback {

		@Override
		public void connectionLost(Throwable paramThrowable) {
			// TODO Auto-generated method stub
			
		}

		@Override
		public void messageArrived(String paramString, MqttMessage paramMqttMessage) throws Exception {
			LOG.error("reciveMsg from "+paramString+" Date:"+DateUtil.now()+" Content:"+paramMqttMessage.toString());
		}

		@Override
		public void deliveryComplete(IMqttDeliveryToken paramIMqttDeliveryToken) {
			// TODO Auto-generated method stub
			
		}
		
	}
}